package com.framework.bdf4j.sysadm.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.framework.bdf4j.annotations.SysLog;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.comm.util.TreeUtils;
import com.framework.bdf4j.sysadm.entity.SysMenu;
import com.framework.bdf4j.sysadm.service.SysMenuService;
import com.framework.bdf4j.sysadm.vo.MenuVO;
import com.framework.bdf4j.sysadm.vo.Ztree;

import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;

@Controller
@AllArgsConstructor
@RequestMapping("/admin/menu")
@Api(value = "menu", tags = "菜单管理模块")
public class SysMenuController {
    private final SysMenuService sysMenuService;

    // 跳转到菜单列表页
    @GetMapping("/index")
    public String goMenu() {
        return "sysadm/menu/menuList";
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree")
    public String selectMenuTree(@RequestParam(required = false) String menuId, ModelMap mmap) {
        SysMenu menu = new SysMenu();
        if (StringUtils.isNotEmpty(menuId)) {
            menu = sysMenuService.getById(menuId);
        }
        mmap.put("menu", menu);
        return "sysadm/menu/tree";
    }

    // 跳转到菜单编辑页
    @GetMapping("/goEditMenu")
    public String goEditMenu(@RequestParam(required = false) String id, @RequestParam String oper, Model model) {
        SysMenu menu = new SysMenu();
        if (!"add".equals(oper)) {
            menu = sysMenuService.getById(Integer.parseInt(id));
            if (Constants.MENU_TREE_ROOT_ID != menu.getParentId())
                menu.setParentName(sysMenuService.getById(menu.getParentId()).getName());
        }
        model.addAttribute("viewobject", menu);
        model.addAttribute("oper", oper);
        return "sysadm/menu/menuEdit";
    }

    /**
     * 分页查询角色信息
     *
     * @param page
     *            分页对象
     * @return 分页对象
     */
    @PostMapping("/list")
    @ResponseBody
    public List<SysMenu> getMenuList(SysMenu sysmenu) {
        if (StringUtils.isEmpty(sysmenu.getType()))
            sysmenu.setType(null);
        if (StringUtils.isEmpty(sysmenu.getName()))
            sysmenu.setName(null);
        return sysMenuService.list(Wrappers.query(sysmenu));
    }

    /**
     * <b>方法描述：</b> 获取当前用户的菜单权限树 <br/>
     *
     * @return 菜单JSON数据
     */
    @ResponseBody
    @GetMapping("/getCheckMenuTree")
    public List<Ztree> getCheckMenuTree(@RequestParam String roleId) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        // 查询所有菜单
        List<SysMenu> menuList = sysMenuService.list(Wrappers.<SysMenu>lambdaQuery().orderByAsc(SysMenu::getSort));
        if (StringUtils.isNotBlank(roleId)) {
            List<Integer> permlist = sysMenuService.findMenuByRoleId(Integer.valueOf(roleId)).stream()
                .map(MenuVO::getMenuId).collect(Collectors.toList());

            ztrees = TreeUtils.initMenuZtree(menuList, permlist);
        } else {
            ztrees = TreeUtils.initMenuZtree(menuList, null);
        }
        return ztrees;
    }

    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @ResponseBody
    @GetMapping(value = "/tree")
    public List<Ztree> getTree() {
        return sysMenuService.selectTree();
    }

    /**
     * 新增菜单
     *
     * @param sysMenu
     *            菜单信息
     * @return success/false
     */
    @SysLog("新增菜单")
    @ResponseBody
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys_menu_add')")
    public R save(SysMenu sysMenu) {
        if (sysMenu.getParentId() == null)
            sysMenu.setParentId(Constants.MENU_TREE_ROOT_ID);
        return R.ok(sysMenuService.save(sysMenu));
    }

    /**
     * 删除菜单
     *
     * @param id
     *            菜单ID
     * @return success/false
     */
    @SysLog("删除菜单")
    @ResponseBody
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sys_menu_del')")
    public R removeById(@PathVariable Integer id) {
        return sysMenuService.removeMenuById(id);
    }

    /**
     * 更新菜单
     *
     * @param sysMenu
     * @return
     */
    @SysLog("更新菜单")
    @ResponseBody
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys_menu_edit')")
    public R update(SysMenu sysMenu) {
        return R.ok(sysMenuService.updateMenuById(sysMenu));
    }
}
